const { readFileSync, writeFileSync } = require("fs")
const { ethers, network } = require("hardhat")
const path = require("path")

const FRONT_END_ADDRESSES_FILE = "../../../react/nextjs-smartcontract-lottery-fcc/constants/contractAddresses.json"
const FRONT_END_ABI_FILE = "../../../react/nextjs-smartcontract-lottery-fcc/constants/abi.json"
const RAFFLE_ARTIFACT_PATH = path.join(__dirname, "../artifacts/contracts/Raffle.sol/Raffle.json")

module.exports = async () => {
    if (process.env.UPDATE_FRONT_END) {
        console.log("Updating front end...")
        updateContractAddress()
        updateAbi()
    }
}

async function updateContractAddress() {
    const raffle = await ethers.getContract("Raffle")
    const chainId = network.config.chainId.toString()
    const contractAddresses = JSON.parse(readFileSync(FRONT_END_ADDRESSES_FILE, "utf8"))
    if (chainId in contractAddresses) {
        if (!contractAddresses[chainId].includes(raffle.target)) {
            contractAddresses[chainId].push(raffle.target)
        }   
    } else {
        contractAddresses[chainId] = [raffle.target]
    }
    writeFileSync(FRONT_END_ADDRESSES_FILE, JSON.stringify(contractAddresses))
    console.log("Front end contractAddress written!")
}

async function updateAbi() {
    const raffle = await ethers.getContract("Raffle")
    // ethers V6 不再返回标准的 JSON 格式，直接从 Hardhat 编译产物中读取 ABI
    const artifact = JSON.parse(readFileSync(RAFFLE_ARTIFACT_PATH, "utf8"))
    writeFileSync(FRONT_END_ABI_FILE, JSON.stringify(artifact.abi, null, 2))
    console.log("Front end ABI written!")
}

module.exports.tags = ["all", "frontend"]
